package com.lbj.Dao;


import com.lbj.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao{

    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //添加的方法
    @Override
    public void add(Book book) {
        //sql语句
        String sql = "insert into student values(?,?)";
        //调用方法实现
        Object[] arg = {book.getId(), book.getUserName()};
        int update = jdbcTemplate.update(sql, arg);
        System.out.println(update);
    }

    //修改的方法
    @Override
    public void update(Book book) {
        String sql = "update student set user_name=? where id=?";
        Object[] arg = {book.getUserName(),book.getId()};
        int update = jdbcTemplate.update(sql, arg);
        System.out.println(update);
    }

    //删除的方法
    @Override
    public void delete(String id) {
        String sql = "delete from student where id=?";
        Object[] arg = {id};
        int update = jdbcTemplate.update(sql, arg);
        System.out.println(update);
    }

    //查询表记录数
    @Override
    public int count() {
        String sql = "select count(1) from student";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from student where id=?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class),id);
        return book;
    }

    //查询返回集合
    @Override
    public List<Book> findAllBookInfo() {
        String sql = "select * from student";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

    //批量添加
    @Override
    public void batchAddBook(List<Object[]> batchArgs) {
        String sql = "insert into student values (?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    //批量删除
    @Override
    public void batchDeleteBook(List<Object[]> batchArgs) {
        String sql = "delete from student where id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    //批量修改
    @Override
    public void batchUpdateBook(List<Object[]> batchArgs) {
        String sql = "update student set user_name=? where id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

}
